<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Bret {

    //put your code here
    public $id;
    public $userId;
    public $author;
    public $name;
    public $description;
    public $alias;
    public $dateCreated;
    public $dateModified;
    public $folderId;
    public $data;
    public $privacy;
    public $sharedFrom;
    public $deleted;
    public $images;

    public function __construct() {
        //allocate your stuff
    }

    /**
     * Read folder infos from the database
     * @param Int $id
     */
    public static function withId($id) {
        $instance = new self();
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM brets WHERE id = '$id'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->bretId = $rows["id"];
                $instance->id = $rows["id"];
                $instance->name = $rows["name"];
                $instance->description = $rows["description"];
                $instance->userId = $rows["userid"];
                $instance->folderId = $rows["folderid"];
                $instance->alias = $rows["alias"];
                $instance->dateCreated = new DateTime($rows["datecreated"]);
                if($rows["datemodified"] != "0000-00-00 00:00:00") {
                    $instance->dateModified = new DateTime($rows["datemodified"]);
                } else {
                    $instance->dateModified = new DateTime($rows["datecreated"]);
                }
                $instance->data = $rows["data"];
                $instance->privacy = $rows["privacy"];
                $instance->sharedFrom = $rows["sharedfrom"];
                $instance->deleted = $rows["deleted"];
                $instance->images = Image::withBretId($instance->id);
                $instance->author = User::withId($instance->userId);
                return $instance;
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any folder with provided id");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    /**
     * Create new Folder object to store
     * @param Int $userid
     * @param String $folderName
     * @param Int $parentId
     */
    public static function withData($userid, $bretName, $folderId, $data) {
        $instance = new self();
        $instance->userId = $userid;
        $instance->name = $bretName;
        $instance->folderId = $folderId;
        $instance->data = $data;
        return $instance;
    }

    public static function getId($name) {
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM brets WHERE name = '$name'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                return $rows["id"];
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any folder with provided id");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    public static function getExplore() {
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM brets WHERE deleted = 0 ORDER BY datecreated DESC");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                $brets = array();
                foreach ($result->dataTable->rows as $row) {
                    $bret = new self();
                    $bret->bretId = $row["id"];
                    $bret->id = $row["id"];
                    $bret->name = $row["name"];
                    $bret->description = $row["description"];
                    $bret->userId = $row["userid"];
                    $bret->author = User::withId($row["userid"]);
                    $bret->author->password = "unknown";
                    $bret->folderId = $row["folderid"];
                    $bret->alias = $row["alias"];
                    $bret->dateCreated = $row["datecreated"];
                    $bret->dateModified = $row["datemodified"];
                    $bret->data = $row["data"];
                    $bret->privacy = $row["privacy"];
                    $bret->sharedFrom = $row["sharedfrom"];
                    $bret->deleted = $row["deleted"];
                    $bret->images = Image::withBretId($bret->id);
                    $brets[] = $bret;
                }
                return $brets;
            }
        }
    }

    public static function getBrets($userId) {
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM brets WHERE userid = '$userId' AND deleted = 0 ORDER BY datecreated DESC");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                $brets = array();
                foreach ($result->dataTable->rows as $row) {
                    $bret = new self();
                    $bret->bretId = $row["id"];
                    $bret->id = $row["id"];
                    $bret->name = $row["name"];
                    $bret->description = $row["description"];
                    $bret->userId = $row["userid"];
                    $bret->author = User::withId($row["userid"]);
                    $bret->author->password = "unknown";
                    $bret->folderId = $row["folderid"];
                    $bret->alias = $row["alias"];
                    $bret->dateCreated = $row["datecreated"];
                    $bret->dateModified = $row["datemodified"];
                    $bret->privacy = $row["privacy"];
                    $bret->sharedFrom = $row["sharedfrom"];
                    $bret->deleted = $row["deleted"];
                    $bret->images = Image::withBretId($bret->id);
                    $brets[] = $bret;
                }
                return $brets;
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any bret with provided user id");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }
    
     public static function getMostSharedBrets($limit) {
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM brets WHERE deleted = 0 ORDER BY sharedfrom DESC LIMIT $limit");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                $brets = array();
                foreach ($result->dataTable->rows as $row) {
                    $bret = new self();
                    $bret->bretId = $row["id"];
                    $bret->id = $row["id"];
                    $bret->name = $row["name"];
                    $bret->description = $row["description"];
                    $bret->userId = $row["userid"];
                    $bret->author = User::withId($row["userid"]);
                    $bret->author->password = "unknown";
                    $bret->folderId = $row["folderid"];
                    $bret->alias = $row["alias"];
                    $bret->dateCreated = $row["datecreated"];
                    $bret->dateModified = $row["datemodified"];
                    $bret->privacy = $row["privacy"];
                    $bret->sharedFrom = $row["sharedfrom"];
                    $bret->deleted = $row["deleted"];
                    $bret->images = Image::withBretId($bret->id);
                    $brets[] = $bret;
                }
                return $brets;
            } else {
                $controller = new ErrorController(new Error(), new ErrorView(), "404", "Not found any bret with provided user id");
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    public static function saveBret($id, $userid, $name, $description, $alias, $folderid, $data) {
        $db = Database::getInstance();
        if ($id == 0) {
            $id = $db->getID('brets', 'id');
            $privacy = 0;
            $sharefrom = 0;
            $deleted = 0;
            $query = "INSERT INTO brets (id, userid, name, description, alias, folderid, data, privacy, sharedfrom, deleted) "
                    . "VALUES ('$id', '$userid', '$name', '$description', '$alias', '$folderid', '$data', '$privacy', '$sharefrom', '$deleted')";
        } else {
            $datemodified = date('Y-m-d H:i:s');
            $query = "UPDATE brets SET data='$data', datemodified='$datemodified'  WHERE id='$id'";
        }
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            return 'succeed';
        } else {
            return 'fail';
        }
    }

    public static function getBretData($id) {
        $db = Database::getInstance();
        $result = $db->query("SELECT data FROM brets WHERE id='$id'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                return $row['data'];
            } else {
                $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
                $controller->returnError();
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    public static function deleteMulti($ids) {
        $db = Database::getInstance();
        $query = "UPDATE brets SET deleted = '1' WHERE id IN (";
        for ($i = 0; $i < sizeof($ids); $i++) {
            if($i == sizeof($ids) - 1) {
                $query .= $ids[$i].")";
            } else {
                $query .= $ids[$i].', ';
            }
        }
        $result = $db->query($query);
        if($result->returnCode == 200) {
            return 'succeed';
        } else {
            return 'failed';
        }
    }
    
    public static function restoreMulti($ids) {
        $db = Database::getInstance();
        $query = "UPDATE brets SET deleted = '0' WHERE id IN (";
        for ($i = 0; $i < sizeof($ids); $i++) {
            if($i == sizeof($ids) - 1) {
                $query .= $ids[$i].")";
            } else {
                $query .= $ids[$i].', ';
            }
        }
        $result = $db->query($query);
        if($result->returnCode == 200) {
            return 'succeed';
        } else {
            return 'failed';
        }
    }
}
